package com.scalar.chiptrack.sales.actions.quote;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.ContactPerson;
import com.scalar.chiptrack.sales.Quotation;
import com.scalar.chiptrack.sales.actions.SalesOrderAction;
import com.scalar.chiptrack.sales.dao.*;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.SelectCustomerForm;
import com.scalar.chiptrack.sales.forms.quote.QuotationForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;

public final class SelectCustomerForQuoteAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/selectCustomerForQuote.do";  // Added by Basha (08/08/2003)

    // ----------------------------------------------------- Instance Variables


    // --------------------------------------------------------- Public Methods

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {
        String customerName = null;
        ArrayList customersList = null;
        // Extract attributes and parameters we will need
        SelectCustomerForm subform = ( SelectCustomerForm ) form;
        String action = request.getParameter ( "action" );
        int isSample = 1; //default set to salesOrder
        if ( ( request.getParameter ( "isSample" ) != null ) && ( request.getParameter ( "isSample" ).length () == 0 ) )
            isSample = Integer.parseInt ( request.getParameter ( "isSample" ) );
        //Get the session, to retrieve the values
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        /* Commented by Prabhanjan, Sep 16, 2004
        // Great Plains Sales Integration Re-direction -----------------------------------------------------------
        // Prabhanjan on Feb 25, 2004
        if ( Constants.FINANCE_INTEGRATION_TYPE_GREAT_PLAINS.equalsIgnoreCase ( ConfigManager.getFinanceIntegrationType () ) == true )
        {
            return new GPSelectCustomerForQuoteAction ().execute ( mapping, form, request, response );
        }
        // Great Plains Re-direction -----------------------------------------------------------
        */
        String showModify = "FALSE";
        if ( user.isActionAllowed ( Functionality.CUSTOMER_DETAILS, User.USER_ACTION_VIEW ) )
            showModify = "TRUE";
        request.setAttribute ( "showNewCustomerLink", showModify );


        // Validate the request parameters specified by the user
        HashMap errors = new HashMap ();
        if ( action == null )
            action = "SelectCustomer";
        if ( "SelectCustomer".equals ( action ) )
        {

            /* Commented by Rohan on June 30th 2004
            //Added by rohan on June 4th 2004 for exporting the new sales order from Epicore to CT
            //checking if sales is integrated with Epicore
            if( Constants.SALES_INTEGRATION_TYPE_EPICORE.equals( ConfigManager.getSalesIntegrationType() ) )
            {
                EPISalesOrderDAO.updateChiptracWithEpicoreSalesOrderDetails( user, true );
            }
            */
            //Set all the attributes in the request....
            request.setAttribute ( "customers", NewCustomerDAO.getAllCustomerNamesByUserTypeBySetup ( null, user, null, isSample ) );
            request.setAttribute ( "showList", "FALSE" );

            // Forward control to the specified success URL
            return ( mapping.findForward ( "customerList" ) );

        }

        if ( "DisplayCustomerSearch".equals ( action ) )
        {
            subform.setCustomerName ( "" );
            subform.setSelectedCustomer ( "0" );
            request.setAttribute ( "customers", NewCustomerDAO.getAllCustomerNamesByUserTypeBySetup ( null, user, null, isSample ) );
            request.setAttribute ( "showList", "FALSE" );
            return ( mapping.findForward ( "customerList" ) );
        }

        if ( "SearchCustomer".equals ( action ) )
        {
            //here using the property utils we can get the form value
            customerName = BeanUtils.getSimpleProperty ( form, "customerName" );
            String selectedCustomer = BeanUtils.getSimpleProperty ( form, "selectedCustomer" );

            if ( Integer.parseInt ( selectedCustomer ) == 0 )
            {
                customersList = CustomerDAO.getAllCustomers ( customerName.replaceAll("_","[_]").replaceAll("%","[%]"), user, isSample );
                request.setAttribute ( "customersList", customersList );
                request.setAttribute ( "customers", NewCustomerDAO.getAllCustomerNamesByUserTypeBySetup ( null, user, null,isSample ) );


                if ( customersList.size () == 0 )
                {
                    errors.put ( ERROR_CUSTOMER_NOT_FOUND, null );
                }
                else
                {
                    request.setAttribute ( "showList", "TRUE" );
                }

                if ( !errors.isEmpty () )
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                return ( mapping.findForward ( "customerList" ) );
            }
            else
            {
                QuotationForm quotationForm = new QuotationForm ();
                Quotation quotation = QuotationDAO.getQuotationCustomerDetails ( selectedCustomer ) ;
                ArrayList prevQuotationList = null;
                ArrayList prevQuotationPriceList = null;
                HashMap  quotationMap = ( HashMap ) session.getAttribute( "quotationMap" );
                if ( quotationMap == null ) {
                    quotationMap = new HashMap();
                }
                quotationMap.put( selectedCustomer, quotation );
                session.setAttribute( "quotationMap", quotationMap );
                PropertyUtils.copyProperties ( quotationForm, quotation );

                quotationForm.setQuotationNo ( QuotationDAO.getAutomatedQuoteNo () );

                if ( quotationForm.getShippingMethodName () != null )
                {
                    quotationForm.setShippingMethodName ( quotationForm.getShippingMethodName ().trim () );
                }
                if ( quotationForm.getShippingAccount () != null )
                {
                    quotationForm.setShippingAccount ( quotationForm.getShippingAccount ().trim () );
                }

                request.setAttribute ( "Account", quotationForm.getShippingMethodName () + "   #   " + quotationForm.getShippingAccount () );
                request.setAttribute ( "Method", quotationForm.getShippingMethodName () + "   #   " + quotationForm.getShippingAccount () );

                ArrayList lineItems = getLineItems ( session );
                request.setAttribute ( "lineItems", lineItems );
                //Added by Prabhanjan on 07 Mar 2004
                request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );

                //request.setAttribute ( "shippingMethods", quotationForm.getShippingMethods () );
                session.setAttribute ( "shippingInstructions", NewSalesOrderDAO.loadShippingInstructions( null ) );
                session.setAttribute ( "freightInstructions", NewSalesOrderDAO.loadFreightInstructions( null ) );

                request.setAttribute ( "mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers () );
                request.setAttribute ( "quoteTypes", QuotationDAO.getQuoteTypeLabelValueList( null ) );
                request.setAttribute ( "applications", QuotationDAO.getQuoteApplicationLabelValueList( null ) );
                request.setAttribute ( "screenDisplayFiledsList", QuotationDAO.getScreenDisplayFiledsList( null ) );

                //Added by Sarada 24th Feb 2004 to get Customer PartNos of selected mfg part nos
                //request.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNosOfCustomer ( quotationForm.getCustomerId () ) );
                //request.setAttribute ( "mfgPartsWithComments", SalesOrderDAO.loadAllManfacturingPartNumbersWithComments ( quotationForm.getCustomerId () ) );
                //request.setAttribute ( "mfgPartsWithCustomerPartNos", NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( quotationForm.getCustomerId (), quotationForm.getOdmId() ) );
                //request.setAttribute ( "mfgPartsWithLabelNumbers", NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( quotation.getCustomerId (), quotation.getOdmId() ) );
                quotation.setMfgParts( SalesOrderDAO.loadAllManfacturingPartNosOfCustomerWithOutobsolete ( quotationForm.getCustomerId (), isSample ) );
                quotation.setMfgPartsWithComments( SalesOrderDAO.loadAllManfacturingPartNumbersWithComments ( quotationForm.getCustomerId (), isSample ) );
                quotation.setMfgPartsWithCustomerPartNos( NewSalesOrderDAO.loadManfacturingPartNumbersWithCustomerPartNumbers ( quotationForm.getCustomerId (), quotationForm.getOdmId(), isSample ) );
                quotation.setMfgPartsWithLabelNumbers( NewSalesOrderDAO.loadManfacturingPartNumbersWithOdmLabelNumbers ( quotation.getCustomerId (), quotation.getOdmId(), isSample ) );
                session.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
                // Added by veeru on 26th April 2004
                Address addressObject = CustomerDAO.getAddress ( quotation.getBillingAddressId () );
                ContactPerson contactPerson = new ContactPerson();
                contactPerson.setContactPerson(quotation.getCustomerName());
                contactPerson.setPhoneNumber(addressObject.getPhoneNumber());
                contactPerson.setCellNumber("");
                contactPerson.setFaxNumber(addressObject.getFaxNumber());
                contactPerson.setEmail(addressObject.getEmail());
                HashMap customerContactPersonMap = CustomerDAO.getContactPersonDetailsMap ( quotationForm.getCustomerId () );
                customerContactPersonMap.put(subform.getCustomerName(),contactPerson);
                //request.setAttribute ( "customerContactPersonsMap", customerContactPersonMap );
                //request.setAttribute ( "contactPersons", quotation.getContactPersons() );
                //request.setAttribute ( "billingAddressContactPersons", quotation.getContactPersonsForBillingAddress() );
                //request.setAttribute ( "shippingAddressContactPersons", quotation.getContactPersonsForShippingAddress() );
                quotation.setCustomerContactPersonMap( customerContactPersonMap );

                HashMap billingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getBillingAddressId() , quotation.getBillingAddressAsObject ());
                addressObject.setContactPerson("");
                addressObject.setCellNumber("");
                billingAddressMap.put("",addressObject.getAddressAsString());
                HashMap shippingAddressMap = CustomerDAO.getAddressDetailsMap ( quotation.getShippingAddressId() , quotation.getShippingAddressAsObject ());
                Address shipAddress = CustomerDAO.getAddress ( quotation.getShippingAddressId () );
                shippingAddressMap.put("",shipAddress.getAddressWithoutContactPersonAsString());
                //request.setAttribute ( "billingAddressMap", billingAddressMap  );
                //request.setAttribute ( "shippingAddressMap", shippingAddressMap );
                quotation.setBillingAddressMap( billingAddressMap );
                quotation.setShippingAddressMap( shippingAddressMap );
                session.setAttribute ( "allShippingTerms", quotation.getAllShippingTerms () );
                session.setAttribute ( "allDeliveryTerms", quotation.getAllDeliveryTerms() );
                request.setAttribute ( "endUsers", EndUserDAO.loadAllEndUsersForCustomer ( Integer.parseInt ( selectedCustomer ) ) );
                //End of Added by Veeru
                //Added by varma 02 aug 2004 to load all Sales Persons,Sales Reps of the customer
                //request.setAttribute("salesPersons",CustomerDAO.loadAllSalesPersonsforCustomer(Integer.parseInt ( selectedCustomer ) )) ;
                //request.setAttribute("salesReps",CustomerDAO.loadAllSalesRepsforCustomer(Integer.parseInt ( selectedCustomer ) ));
                //request.setAttribute("odmList", CustomerRelationshipDAO.getAllOdmsForCustomer( selectedCustomer ));
                //request.setAttribute("shippingAddresses", quotationForm.getShippingAddresses () );
                quotation.setSalesPersons( CustomerDAO.loadAllSalesPersonsforCustomer(Integer.parseInt ( selectedCustomer ) ) );
                quotation.setSalesReps( CustomerDAO.loadAllSalesRepsforCustomer(Integer.parseInt ( selectedCustomer ) ) );
                quotation.setOdmList( CustomerRelationshipDAO.getAllOdmsForCustomer( selectedCustomer ) );
                quotation.setEndCustomerList( CustomerRelationshipDAO.getAllEndCustomersForCustomer( selectedCustomer ) ) ;
                session.setAttribute ( "odmList", quotation.getOdmList());
                session.setAttribute ( "endCustomerList", quotation.getEndCustomerList());
                session.setAttribute ( "quotationTypesList", QuotationAction.getQuotationTypesList() );
                session.setAttribute ( "qtyPerOptionsList", QuotationAction.getQtyPerOptionsList());
                session.setAttribute ( "commitmentsList", QuotationAction.getCommitmentsList());
                session.setAttribute ( "quantityiesList", QuotationAction.getQuantityiesList());
                session.setAttribute ( "priceDiscountOptionsList", QuotationAction.getPriceDiscountOptionsList());
                session.setAttribute ( "rebateGoalsList", QuotationAction.getRebateGoalsList());
                session.setAttribute ( "competitorsList", QuotationDAO.getCompetitors(null));
                prevQuotationList = QuotationDAO.getPrevQuotationDetails(null, quotation.getCustomerId());
                prevQuotationPriceList = QuotationDAO.getPrevQuotationPriceDetails(null, quotation.getCustomerId());
                request.setAttribute("prevQuotationsList", prevQuotationList);
                request.setAttribute("prevQuotationPriceList", prevQuotationPriceList);
                request.setAttribute( "prevCommitmentsDetails", QuotationDAO.getPrevCommitmentsDetails(null, quotation.getCustomerId()));
                saveToken ( request );
                request.setAttribute ( "QuotationForm", quotationForm );
                if (ConfigManager.isLoadQuotationQuestionnaire())
                {
                    return ( mapping.findForward ( "QuotationQuestionnaire" ) );
                }
                else
                {
                    return ( mapping.findForward ( "Quotation" ) );
                }
            }
        }

        return ( mapping.findForward ( "customerList" ) );
    }

    private static ArrayList getLineItems ( HttpSession session )
    {
        ArrayList lineItems = new ArrayList ();

        for ( int i = 1; i < 6; i++ )
        {
            LineItem lineItem = new LineItem ();
            lineItem.setLineItemNo ( i );
            lineItem.setPoLineItemNo ( i );
            lineItems.add ( lineItem );
        }
        session.setAttribute ( "maxLineItemNo", "6" );
        return lineItems;
    }
}
